package com.seeyon.apps.bense.util;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;

import com.seeyon.apps.bense.common.manager.CAP4FormDataManagerExt;
import com.seeyon.cap4.batch.params.BatchRefreshParams;
import com.seeyon.cap4.batch.service.CAPBatchRefreshService;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.*;
import com.seeyon.cap4.form.exception.FormException;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.cap4.template.constant.CAPBusinessEnum;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.base.result.ServiceResult;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.exceptions.ServerBusyException;
import com.seeyon.ctp.util.ParamUtil;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.bean.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.util.*;

public class SaveToUnFlowUtil {

    private static Log logger = LogFactory.getLog(SaveToUnFlowUtil.class);
    private static FormBean form;
    private static FormFactory formFactory;
    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");

    private static final Map<String, Integer> TYPE_MAP = new HashMap<>();

    static {
        TYPE_MAP.put("VARCHAR", 0);
        TYPE_MAP.put("LONGTEXT", 1);
        TYPE_MAP.put("DATETIME", 2);
        TYPE_MAP.put("TIMESTAMP", 3);
        TYPE_MAP.put("DECIMAL", 4);
        TYPE_MAP.put("HANDWRITE", 5);
    }

    /**
     * @return formFactory
     */
    public FormFactory getFormFactory() {
        return formFactory;
    }

    /**
     * @param formFactory 要设置的 formFactory
     */
    public void setFormFactory(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    public void setCap4FormManager(CAP4FormManager cap4FormManager) {
        this.cap4FormManager = cap4FormManager;
    }

    public static FormBean getForm(String code) throws BusinessException {
        form = cap4FormManager.getFormByFormCode(code);
        return form;
    }

    /**
     * 保存到底表
     *
     * @param senderName           发送人登录账号
     * @param logData              需要传入的参数
     * @param downLoadLogTableCode 底表对象
     */
    public static String saveUnFlowForm(String senderName, Map<String, Object> logData, String downLoadLogTableCode) {
        String res = "";
        FormBean formBean = new FormBean();
        try {
            formBean = getForm(downLoadLogTableCode);//文件下载记录表
        } catch (BusinessException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }

        try {
            FormExport formExport = new FormExport();
            formExport.setFormId(new BigDecimal(0).longValue());
            formExport.setFormName((String) formBean.getAllTableName().get(0));
            List<DefinitionExport> definitions = new ArrayList<>();
            List<ValueExport> values = new ArrayList<>();
            List<DefinitionExport> subDefinitions = new ArrayList<DefinitionExport>(); // 从表的字段定义

            List<FormFieldBean> filedBeans = formBean.getAllFieldBeans();
            for (FormFieldBean fieldBean : filedBeans) {
                if (fieldBean.isMasterField()) {
                    DefinitionExport defExp = new DefinitionExport();
                    defExp.setName(fieldBean.getName());
                    defExp.setType(getIntType(fieldBean.getFieldType()));
                    defExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        defExp.setIsNullable(1);
                    } else {
                        defExp.setIsNullable(0);
                    }
                    defExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    definitions.add(defExp);
                    ValueExport valExp = new ValueExport();
                    valExp.setDisplayName(fieldBean.getDisplay());
                    String value = logData.get(fieldBean.getDisplay()) == null ? "" : logData.get(fieldBean.getDisplay()).toString();
                    valExp.setValue(value);
                    valExp.setDisplayValue(null);
                    values.add(valExp);
                }
                if (fieldBean.isSubField()) {
                    DefinitionExport subExp = new DefinitionExport();
                    subExp.setName(fieldBean.getName());
                    subExp.setType(getIntType(fieldBean.getFieldType()));
                    subExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        subExp.setIsNullable(1);
                    } else {
                        subExp.setIsNullable(0);
                    }
                    subExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    subDefinitions.add(subExp);
                }
            }

            //插入重复表数据
            List<SubordinateFormExport> subordinateForms = new ArrayList<>();
            List<Map<String, Object>> subList = (List<Map<String, Object>>) logData.get("subList");
            if (!subDefinitions.isEmpty() && null != subList) {
                if (!subList.isEmpty()) {
                    for (Map<String, Object> map : subList) {
                        SubordinateFormExport subDfe = new SubordinateFormExport();
                        List<RecordExport> subValues = new ArrayList<RecordExport>(); // 从表的字段记录
                        List<ValueExport> subvalue = new ArrayList<>();
                        subDfe.setDefinitions(subDefinitions);
                        RecordExport reExp = new RecordExport();
                        for (FormFieldBean fieldBean : filedBeans) {
                            if (fieldBean.isSubField()) {
                                ValueExport valExp = new ValueExport();
                                valExp.setDisplayName(fieldBean.getDisplay());
                                String value = map.get(fieldBean.getDisplay()) == null ? "" : map.get(fieldBean.getDisplay()).toString();
                                valExp.setValue(value);
                                valExp.setDisplayValue(null);
                                subvalue.add(valExp);
                            }
                        }
                        reExp.setRecord(subvalue);
                        subValues.add(reExp);
                        subDfe.setValues(subValues);
                        subordinateForms.add(subDfe);
                    }
                    //保存重复表数值
                    formExport.setSubordinateForms(subordinateForms);
                }
            }
            //保存主表数值
            formExport.setDefinitions(definitions);
            formExport.setValues(values);

            if (formFactory == null) {
                formFactory = (FormFactory) AppContext.getBean("formFactory");
            }
            formFactory.importBusinessFormData(senderName, downLoadLogTableCode, formExport, null);
        } catch (Exception e) {
            logger.info("保存到底表报错", e);
            res = "保存到底表报错" + e;
            throw new ServerBusyException(e.getMessage());
        }
        return res;
    }

    public static Long saveUnFlowFormId(String senderName, Map<String, Object> logData, String downLoadLogTableCode) {
        FormBean formBean;
        try {
            formBean = getForm(downLoadLogTableCode);//文件下载记录表
        } catch (BusinessException ignored) {
            return null;
        }
        try {
            FormExport formExport = new FormExport();
            formExport.setFormId(new BigDecimal(0).longValue());
            formExport.setFormName((String) formBean.getAllTableName().get(0));
            List<DefinitionExport> definitions = new ArrayList<>();
            List<ValueExport> values = new ArrayList<>();
            List<DefinitionExport> subDefinitions = new ArrayList<DefinitionExport>(); // 从表的字段定义

            List<FormFieldBean> filedBeans = formBean.getAllFieldBeans();
            for (FormFieldBean fieldBean : filedBeans) {
                if (fieldBean.isMasterField()) {
                    DefinitionExport defExp = new DefinitionExport();
                    defExp.setName(fieldBean.getName());
                    defExp.setType(getIntType(fieldBean.getFieldType()));
                    defExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        defExp.setIsNullable(1);
                    } else {
                        defExp.setIsNullable(0);
                    }
                    defExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    definitions.add(defExp);
                    ValueExport valExp = new ValueExport();
                    valExp.setDisplayName(fieldBean.getDisplay());
                    String value = logData.get(fieldBean.getDisplay()) == null ? "" : logData.get(fieldBean.getDisplay()).toString();
                    valExp.setValue(value);
                    valExp.setDisplayValue(null);
                    values.add(valExp);
                }
                if (fieldBean.isSubField()) {
                    DefinitionExport subExp = new DefinitionExport();
                    subExp.setName(fieldBean.getName());
                    subExp.setType(getIntType(fieldBean.getFieldType()));
                    subExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        subExp.setIsNullable(1);
                    } else {
                        subExp.setIsNullable(0);
                    }
                    subExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    subDefinitions.add(subExp);
                }
            }

            //插入重复表数据
            List<SubordinateFormExport> subordinateForms = new ArrayList<>();
            List<Map<String, Object>> subList = (List<Map<String, Object>>) logData.get("subList");
            if (!subDefinitions.isEmpty() && null != subList) {
                if (!subList.isEmpty()) {
                    for (Map<String, Object> map : subList) {
                        SubordinateFormExport subDfe = new SubordinateFormExport();
                        List<RecordExport> subValues = new ArrayList<RecordExport>(); // 从表的字段记录
                        List<ValueExport> subvalue = new ArrayList<>();
                        subDfe.setDefinitions(subDefinitions);
                        RecordExport reExp = new RecordExport();
                        for (FormFieldBean fieldBean : filedBeans) {
                            if (fieldBean.isSubField()) {
                                ValueExport valExp = new ValueExport();
                                valExp.setDisplayName(fieldBean.getDisplay());
                                String value = map.get(fieldBean.getDisplay()) == null ? "" : map.get(fieldBean.getDisplay()).toString();
                                valExp.setValue(value);
                                valExp.setDisplayValue(null);
                                subvalue.add(valExp);
                            }
                        }
                        reExp.setRecord(subvalue);
                        subValues.add(reExp);
                        subDfe.setValues(subValues);
                        subordinateForms.add(subDfe);
                    }
                    //保存重复表数值
                    formExport.setSubordinateForms(subordinateForms);
                }
            }
            //保存主表数值
            formExport.setDefinitions(definitions);
            formExport.setValues(values);

            if (formFactory == null) {
                formFactory = (FormFactory) AppContext.getBean("formFactory");
            }
            Map<String, Object> relevantParam = new HashMap<>();
            return formFactory.importBusinessForm(senderName, downLoadLogTableCode, formExport, null, relevantParam);
        } catch (Exception e) {
            logger.info("保存到底表报错", e);
            throw new ServerBusyException(e.getMessage());
        }
    }

    private static int getIntType(String type) {
        if (type == null) {
            throw new IllegalArgumentException("Type cannot be null");
        }
        String upperType = type.toUpperCase();
        Integer intType = TYPE_MAP.get(upperType);
        if (intType == null) {
            throw new IllegalArgumentException("Unknown type: " + upperType);
        }
        return intType;
    }

    /**
     * 修改动态表数据
     *
     * @param map
     * @param master
     * @param formBean
     * @param refresh
     */
    public static void updateFormData(Map<String, Object> map, FormDataMasterBean master, FormBean formBean, boolean refresh) {
        try {
            logger.info("更新底表数据：" + master.getId() + "==formId:" + formBean.getId());
            master.addFieldValue(map);
            Iterator<String> it = map.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                if (key.equals("subList")) {
                    List<Map<String, Object>> subList = (List<Map<String, Object>>) map.get(key);
                    if (!subList.isEmpty()) {
                        for (Map<String, Object> sub : subList) {
                            String subForm = ParamUtil.getString(sub, "subForm");
                            for (FormTableBean formTableBean : formBean.getSubTableBean()) {
                                if (formTableBean.getTableName().equals(subForm)) {
                                    FormDataSubBean subBean = new FormDataSubBean(formTableBean, master);
                                    for (String subKey : sub.keySet()) {
                                        Object value = sub.get(subKey);
                                        FormFieldBean subFieldBean = formBean.getFieldBeanByDisplay(subKey);
                                        if (subFieldBean != null) {
                                            subBean.addFieldValue(subFieldBean.getName(), value);
                                        }
                                    }
                                    master.addSubData(subForm, subBean);
                                }
                            }
                        }
                    }
                } else {
                    Object value = map.get(key);
                    FormFieldBean fieldBean = formBean.getFieldBeanByDisplay(key);
                    if (fieldBean != null) {
                        master.addFieldValue(fieldBean.getName(), value);
                    }
                }
            }
            FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
            formApi4Cap4.saveOrUpdateFormData(master, formBean.getId(), true);
            //执行刷新，便于自动关联的数据进行关联
            try {
                if (refresh) {
                    logger.info("更新底表数据时进行刷新：" + master.getId() + "==formId:" + formBean.getId());
                    CAPBatchRefreshService capBatchOperationService = (CAPBatchRefreshService) AppContext.getBean("capBatchOperationService");
                    Map<String, Object> params = new HashMap<String, Object>();

                    List<String> refreshDataId = new ArrayList<String>();
                    refreshDataId.add(String.valueOf(master.getId()));
                    params.put("bindAuthId", String.valueOf(formBean.getBind().getId()));
                    params.put("formId", String.valueOf(formBean.getId()));
                    params.put("isDoTrigger", CAPBusinessEnum.TrueOrFalseEnum.FALSE.getKey());
                    params.put("masterIds", refreshDataId);
                    params.put("size", String.valueOf(refreshDataId.size()));
//			        capBatchOperationService.updateBatchRefreshData(params);
                }
            } catch (Exception e) {
                logger.error("刷新底表数据出错:", e);
                throw new FormException(e.getMessage());
            }

        } catch (Exception e) {
            logger.error("更新底表数据出错:", e);
            throw new FormException(e.getMessage());
        }
    }

    public static void saveOrUpdateFormData(FormDataMasterBean master, FormBean formBean) {
        try {
            if (null == AppContext.getCurrentUser()) {
                FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
                formApi4Cap4.saveOrUpdateFormData(master, formBean.getId(), true);
            }else {
                FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
                formApi4Cap4.saveOrUpdateFormData(master, formBean.getId(), true);
//                CAP4SessionFormDataManager cap4SessionFormDataManager = (CAP4SessionFormDataManager) AppContext.getBean("cap4SessionFormDataManager");
//                cap4SessionFormDataManager.put2Cache(master, AppContext.currentUserId());
            }
        } catch (Exception e) {
            throw new FormException(e.getMessage());
        }
    }

    public static void saveOrUpdateFormData(FormBean formBean, Map<String, Object> formParams) {
        saveOrUpdateFormData(formBean, formParams, true);
    }

    public static void saveOrUpdateFormData(FormBean formBean, Map<String, Object> formParams, boolean fillNull) {
        try {
            Map<String, Object> masterParams = new HashMap<>();
            Map<String, Object> subParams = new HashMap<>();
            for (Map.Entry<String, Object> entry : formParams.entrySet()) {
                if (entry.getValue() instanceof Collection) {
                    subParams.put(entry.getKey(), entry.getValue());
                }else {
                    masterParams.put(entry.getKey(), entry.getValue());
                }
            }
            CAP4FormDataManagerExt cap4FormDataManagerExt = (CAP4FormDataManagerExt) AppContext.getBean("cap4FormDataManagerExt");
            Long masterId = null;
            if (formParams.containsKey("id")) {
                masterId = MapUtil.getLong(formParams, "id");
            }
            List<FormDataMasterBean> exists = null;
            if (null != masterId) {
                exists = cap4FormDataManagerExt.selectMasterDataById(new Long[]{masterId}, formBean, null);
            }

            FormDataMasterBean formDataMasterBean;
            // 新增
            if (CollectionUtils.isEmpty(exists)) {
                formDataMasterBean = new FormDataMasterBean(formBean.getMasterTableBean());
                if (null != masterId) {
                    formDataMasterBean.setId(masterId);
                }
            }else {
                formDataMasterBean = exists.get(0);
            }
            // 主表
            for (Map.Entry<String, Object> materEntry : masterParams.entrySet()) {
                FormFieldBean fieldBean = formBean.getMasterTableBean().getFieldBeanByDisplay(materEntry.getKey());
                if (null == fieldBean) {
                    continue;
                }
                if (!fillNull && null == materEntry.getValue()) {
                    continue;
                }
                formDataMasterBean.addFieldValue(fieldBean.getName(), materEntry.getValue());
            }
            Set<String> clearDtlSet = MapUtil.get(subParams, "clearDtl", new TypeReference<Set<String>>() {
            }, new HashSet<>());
            // 明细
            for (Map.Entry<String, Object> subEntry : subParams.entrySet()) {
                FormTableBean tableBean = formBean.getSubTableBean().stream()
                        .filter(item -> item.getDisplay().equals(subEntry.getKey()))
                        .findFirst()
                        .orElse(null);
                if (null == tableBean) {
                    continue;
                }
                List<FormDataSubBean> subDatas = formDataMasterBean.getSubData(tableBean.getTableName());
                if (null == subDatas) {
                    subDatas = new ArrayList<>();
                }
                if (!subDatas.isEmpty()){
                    if (clearDtlSet.contains(tableBean.getDisplay())) {
                        subDatas.clear();
                    }
                }
                List<Map<String,Object>> dtlDatas = (List<Map<String, Object>>) subEntry.getValue();
                for (Map<String, Object> dtlData : dtlDatas) {
                    Long subId = MapUtil.getLong(dtlData, "id");
                    if (null == subId) {
                        FormDataSubBean formDataSubBean = new FormDataSubBean(tableBean, formDataMasterBean, new boolean[]{fillNull});
                        formDataSubBean.setDb(true);
                        combineSub(fillNull, dtlData, formDataSubBean, subDatas);
                        continue;
                    }
                    FormDataSubBean formDataSubBean = subDatas.stream().filter(item -> item.getId().equals(subId)).findFirst().orElse(null);
                    if (null == formDataSubBean) {
                        formDataSubBean = new FormDataSubBean(tableBean, formDataMasterBean, new boolean[]{fillNull});
                        formDataSubBean.setId(subId);
                        formDataSubBean.setDb(true);
                        combineSub(fillNull, dtlData, formDataSubBean, subDatas);
                        continue;
                    }
                    combineSub(fillNull, dtlData, formDataSubBean, null);
                }

                formDataMasterBean.setSubData(tableBean.getTableName(), subDatas);
            }
            saveOrUpdateFormData(formDataMasterBean, formBean);
        } catch (Exception e) {
            throw new FormException(e.getMessage());
        }
    }

    private static void combineSub(boolean fillNull, Map<String, Object> dtlData, FormDataSubBean formDataSubBean, List<FormDataSubBean> subDatas) {
        if (null == subDatas) {
            return;
        }
        for (Map.Entry<String, Object> subFieldDataEntry : dtlData.entrySet()) {
            FormFieldBean subFormFieldBean = formDataSubBean.getFormTable().getFieldBeanByDisplay(subFieldDataEntry.getKey());
            if (null == subFormFieldBean) {
                continue;
            }
            if (!fillNull && null == subFieldDataEntry.getValue()) {
                continue;
            }
            formDataSubBean.addFieldValue(subFormFieldBean.getName(), subFieldDataEntry.getValue());
        }
        subDatas.add(formDataSubBean);
    }

    public static ServiceResult<?> refresh(FormBean formBean, List<String> masterIds) throws BusinessException {
        User currentUser = AppContext.getCurrentUser();
        if (null == currentUser) {
            return null;
        }
        Long authId;
        List<FormBindAuthBean> unflowFormBindAuthByUserId = formBean.getBind().getUnflowFormBindAuthByUserId(AppContext.getCurrentUser().getId());
        if (CollectionUtils.isEmpty(unflowFormBindAuthByUserId)) {
            List<FormFlowBusinessBean> flowBusinessByUserId = formBean.getBind().getFlowBusinessByUserId(currentUser.getId());
            if (CollectionUtils.isEmpty(flowBusinessByUserId)) {
                return null;
            }
            authId = flowBusinessByUserId.get(0).getId();
        }else {
            authId = unflowFormBindAuthByUserId.get(0).getId();
        }

        CAPBatchRefreshService capBatchOperationService = (CAPBatchRefreshService) AppContext.getBean("capBatchRefreshService");
        List<String> refreshDataId = new ArrayList<>();
        refreshDataId.add(String.valueOf(formBean.getId()));
        BatchRefreshParams batchRefreshParams = new BatchRefreshParams();
        batchRefreshParams.setBindAuthId(authId);
        batchRefreshParams.setFormId(formBean.getId());
        batchRefreshParams.setMasterIds(masterIds);
        batchRefreshParams.setSize(refreshDataId.size());
        batchRefreshParams.setDataConditions(new ArrayList<>());
        batchRefreshParams.setUserConditions(new ArrayList<>());
        batchRefreshParams.setExecuteRelation(true);
        return capBatchOperationService.batchRefresh(batchRefreshParams);
    }

    public static Long saveOrUpdateFormDataWithValid(String formCode, String[] valiFieldAry, Map<String, Object> formParams) {
        return saveOrUpdateFormDataWithValid(null, formCode, valiFieldAry, formParams);
    }

    public static Long saveOrUpdateFormDataWithValid(String senderName, String formCode, String[] valiFieldAry, Map<String, Object> formParams) {
        if (null == senderName) {
            senderName = Optional.ofNullable(AppContext.getCurrentUser()).map(User::getLoginName).orElseThrow(() -> new FormException("保存表单数据异常：请传入操作人工号!"));
        }
        Map<String, Object> masterParams = new HashMap<>();
        Map<String, Object> subParams = new HashMap<>();
        for (Map.Entry<String, Object> entry : formParams.entrySet()) {
            if (entry.getValue() instanceof Collection) {
                subParams.put(entry.getKey(), entry.getValue());
            }else {
                masterParams.put(entry.getKey(), entry.getValue());
            }
        }
        FormBean formBean;
        try {
            formBean = getForm(formCode);//文件下载记录表
        } catch (BusinessException ignored) {
            return null;
        }
        try {
            FormExport formExport = new FormExport();
            formExport.setFormId(new BigDecimal(0).longValue());
            formExport.setFormName((String) formBean.getAllTableName().get(0));
            List<DefinitionExport> definitions = new ArrayList<>();
            List<ValueExport> values = new ArrayList<>();
            List<DefinitionExport> subDefinitions = new ArrayList<DefinitionExport>(); // 从表的字段定义

            List<FormFieldBean> filedBeans = formBean.getAllFieldBeans();
            for (FormFieldBean fieldBean : filedBeans) {
                if (fieldBean.isMasterField()) {
                    DefinitionExport defExp = new DefinitionExport();
                    defExp.setName(fieldBean.getName());
                    defExp.setType(getIntType(fieldBean.getFieldType()));
                    defExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        defExp.setIsNullable(1);
                    } else {
                        defExp.setIsNullable(0);
                    }
                    defExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    definitions.add(defExp);
                    ValueExport valExp = new ValueExport();
                    valExp.setDisplayName(fieldBean.getDisplay());
                    String value = masterParams.get(fieldBean.getDisplay()) == null ? "" : masterParams.get(fieldBean.getDisplay()).toString();
                    valExp.setValue(value);
                    valExp.setDisplayValue(null);
                    values.add(valExp);
                }
                if (fieldBean.isSubField()) {
                    DefinitionExport subExp = new DefinitionExport();
                    subExp.setName(fieldBean.getName());
                    subExp.setType(getIntType(fieldBean.getFieldType()));
                    subExp.setDisplayName(fieldBean.getDisplay());
                    if (fieldBean.isNull()) {
                        subExp.setIsNullable(1);
                    } else {
                        subExp.setIsNullable(0);
                    }
                    subExp.setLen(Integer.parseInt(fieldBean.getFieldLength()));
                    subDefinitions.add(subExp);
                }
            }

            //插入重复表数据
            List<SubordinateFormExport> subordinateForms = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(subDefinitions) && MapUtil.isNotEmpty(subParams)) {
                for (Map.Entry<String, Object> subEntry : subParams.entrySet()) {
                    FormTableBean tableBean = formBean.getSubTableBean().stream()
                            .filter(item -> item.getDisplay().equals(subEntry.getKey()))
                            .findFirst()
                            .orElse(null);
                    if (null == tableBean) {
                        continue;
                    }
                    List<Map<String,Object>> dtlDatas = (List<Map<String, Object>>) subEntry.getValue();
                    SubordinateFormExport subDfe = new SubordinateFormExport();
                    List<RecordExport> subValues = new ArrayList<>(); // 从表的字段记录

                    for (Map<String, Object> dtlData : dtlDatas) {
                        List<ValueExport> subvalue = new ArrayList<>();
                        RecordExport reExp = new RecordExport();
                        for (Map.Entry<String, Object> fieldDataEntry : dtlData.entrySet()) {
                            FormFieldBean fieldBeanByDisplay = tableBean.getFieldBeanByDisplay(fieldDataEntry.getKey());
                            if (null == fieldBeanByDisplay) {
                                continue;
                            }
                            ValueExport valExp = new ValueExport();
                            valExp.setDisplayName(fieldDataEntry.getKey());
                            String value = String.valueOf(fieldDataEntry.getValue());
                            valExp.setValue(value);
                            valExp.setDisplayValue(null);
                            subvalue.add(valExp);
                        }
                        reExp.setRecord(subvalue);
                        subValues.add(reExp);
                    }
                    subDfe.setValues(subValues);
                    subordinateForms.add(subDfe);
                }
                //保存重复表数值
                formExport.setSubordinateForms(subordinateForms);
            }
            //保存主表数值
            formExport.setDefinitions(definitions);
            formExport.setValues(values);

            if (formFactory == null) {
                formFactory = (FormFactory) AppContext.getBean("formFactory");
            }
            Map<String, Object> relevantParam = new HashMap<>();
            return formFactory.importBusinessForm(senderName, formCode, formExport, valiFieldAry, relevantParam);
        } catch (Exception e) {
            logger.info("保存到底表报错", e);
            throw new FormException(e.getMessage());
        }
    }
}
